const { $Message } = require('./../../dist/base/index');
import { $stopWuxRefresher, $stopWuxLoader } from '../../dist/index'
const { $Toast } = require('../../dist/base/index');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    current:1,
    pageSize:10,
    //编辑的对象下标
    editIndex: -1,
    toggles: [],
    loadings: [],
    //用户集合
    userList: [],
    // toggle:true,
    //更改角色上拉菜单的显示值
    visible: false,
    //更改角色上拉菜单的选项
    actions: [
      {
        id: 0,
        name: '游客',
        icon: 'addressbook'
      },
      {
        id: 1,
        name: '管理员',
        icon: 'mine'
      },
      {
        id: 2,
        name: '普通用户',
        icon: 'group'
      }
    ],
    //筛选的角色ID
    filterRole: -1,

    items: [],
    count: 10,
    scrollTop: 0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserList(true, true)
    // var windowWidth = wx.getSystemInfoSync().windowWidth;
    // var windowHeight = wx.getSystemInfoSync().windowHeight;
    // //rpx与px单位之间的换算 : 750/windowWidth = 屏幕的高度（rpx）/windowHeight
    // // var scroll_height = 750 * windowHeight / windowWidth - 150;
    // this.setData({
    //   scroll_height: windowHeight 
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 用户项右侧菜单-角色按钮单击事件
   */
  roleHandleClick(e) {
    this.data.editIndex = e.target.dataset.index;
    this.setData({
      visible: true
    })
  },
  /**
   * 用户右侧菜单-状态按钮单击事件
   */
  statusGandleClick(e) {

    this.data.editIndex = e.target.dataset.index;
    let index = e.currentTarget.dataset.index;
    
    this.data.loadings[index] = true;
    this.setData({
      loadings: this.data.loadings
    })

    let status = null

    if (e.currentTarget.dataset.type == "success") {
      //点击启用
      status = 1;


    } else {
      //点击冻结
      status = 0;
      // this.data.userList[index].status = 0;
    }
    // console.log("this.data.editIndex", this.data.editIndex)
    getApp().sendRequest({
      url:"api/user/alterUserStatus",
      data: {
        userId: this.data.userList[this.data.editIndex].id,
        status: status
      },
      success:res => {
        if (res && res.data && res.data.code === 200){
          this.data.userList[index].status = status;

          this.data.toggles[this.data.editIndex] = false;
          this.setData({
            userList: this.data.userList,

            toggles: this.data.toggles
          },()=>{
              this.data.toggles[this.data.editIndex] = true;
              this.setData({
                toggles: this.data.toggles
              }, () => {
                $Message({ content: '状态修改成功！', type: 'success' });
              })
          })
        }else{

          $Message({ content: '状态修改失败！', type: 'error' });
        }
        
        
      },
      fail:err => {
        $Message({ content: '修改状态请求失败', type: 'error' });
      },
      complete:() => {

        this.data.loadings[index] = false;
        this.setData({
          loadings: this.data.loadings,
        })
      }
    })


    

  },
  /**
   * 更改角色上拉菜单-取消项单击事件
   */
  handleCancel() {
    this.setData({
      visible: false
    });
  },
  swipeoutChange(e) {
    // console.log(e)
  },
  /**
   * 更改角色上拉菜单-选项单击事件
   */
  handleClickItem(e) {

    if (this.data.editIndex == -1) {
      this.setData({
        filterRole: e.detail.index,
        visible: false
      })
      this.getUserList(true,true)
      this.closeFilter()
      return;
    }

    this.data.actions[e.detail.index].loading = true;
    this.setData({
      actions: this.data.actions
    })

    //----------------------这里执行修改用户角色api--------------------
    getApp().sendRequest({
      url:'api/user/alterUserRole',
      data:{
        userId: this.data.userList[this.data.editIndex].id,
        role: this.data.actions[e.detail.index].id
      },
      success:res => {
        if(res && res.data && res.data.code ===200){

          this.data.userList[this.data.editIndex].role = this.data.actions[e.detail.index].id;
          this.setData({
            userList: this.data.userList,
          }, () => {
            $Message({ content: '角色修改成功！', type: 'success' });
          })
        }else{
          $Message({ content: '角色修改失败', type: 'error' });
        }
      },
      fail:err => {
        $Message({ content: '修改角色请求失败', type: 'error' });
      },
      complete:() => {

        this.data.actions[e.detail.index].loading = false;
        this.data.toggles[this.data.editIndex] = false;
        this.setData({
          toggles: this.data.toggles
        }, () => {

          this.data.toggles[this.data.editIndex] = true;
          this.setData({
            actions: this.data.actions,
            visible: false,
            toggles: this.data.toggles
          }, () => {
          })
        })
      }
    })


  },
  //筛选按钮单击事件
  filterBtn() {
    this.data.actions.unshift({
      id: -1,
      name: '全部',
      icon: 'activity'
    })
    
    this.setData({
      showFliter: true,
      actions: this.data.actions
    })
  },
  //关闭筛选框
  closeFilter() {
    this.data.actions.shift()
    this.setData({
      showFliter: false,

      actions: this.data.actions
    });
  },
  //筛选框的角色项单击事件
  filterItemViewRole() {
    this.data.editIndex = -1;
    this.setData({
      visible: true
    })
  },
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    })
  },
  //下拉刷新事件开始
  onPulling() {
    // console.log('onPulling')
  },
  //下拉刷新事件完成
  onRefresh() {
    this.getUserList(true)
  },
  //上拉加载更多事件
  onLoadmore() {
    this.getUserList(false)
  },
  //姓名输入框内容修改事件
  nameInputChange({ detail}){
    // console.log(detail, detail.detail.value)
    this.data.name = detail.detail.value
  },
  //查询按钮单击事件
  searchBtnClick(){
    this.getUserList(true,true)
  },
  /**
   * 获取用户列表数据
   * flag：：是否加载第一页(true:加载第一页，加载完覆盖原有的数据，false：往下翻页)
   * loading： 是否开启加载提示
   */
  getUserList(flag, loading){
    if (loading){
      this.setData({
        userList:[]
      })
      $Toast({
        content: '加载中',
        type: 'loading'
      });
    }
    if(flag){
      this.data.current = 1;
    }else{
      this.data.current++
    }
    getApp().sendRequest({
      url:"api/user/getUserByPaging",
      data:{
        current:this.data.current,
        pageSize:this.data.pageSize,
        name:this.data.name,
        role: this.data.filterRole == -1 ? null:this.data.actions[this.data.filterRole].id
      },
      success:res => {


        if(flag){
          this.data.userList = res.data.data.records
        }else{
          this.data.userList = this.data.userList.concat(res.data.data.records)
        }

        this.setData({
          userList: this.data.userList
        },()=>{
          if (res.data.data.pages <= this.data.current) {
            $stopWuxLoader('#wux-refresher', this, true)
          } else {
            $stopWuxLoader()
          }
        })
      },
      complete:()=>{
        $Toast.hide();
      }
    })
  }
})